package com.ruoyi.web.controller.task;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.BywDeliverPositionType;
import com.ruoyi.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.SetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("vitaeSynchV2Task")
public class VitaeSynchV2Task {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IBywEmployeeImportViteaService employeeImportViteaService;

    @Autowired
    private IBywTiktokUserService tiktokUserService;

    @Autowired
    private IBywViteaService viteaService;

    @Autowired
    private IBywStageService stageService;

    @Autowired
    private IBywViteaOwnershipRelationService viteaOwnershipRelationService;

    @Autowired
    private IBywPositionTypeService positionTypeService;

    public void synchVitaeDataByXcxList() {
        logger.info("开始同步简历数据:" + DateUtils.getTime());
        Map<String, BywVitea> viteaMap = initViteaMap();

        Map<String, BywVitea> ultimatelyPooledDateViteaMap = ultimatelyPooledDate();
        for (Map.Entry<String, BywVitea> entry : ultimatelyPooledDateViteaMap.entrySet()) {
            String userPhone = entry.getKey();
            BywVitea bywVitea = entry.getValue();

            //如果原来没有这个简历--新增
            BywVitea bywViteaData = viteaMap.get(userPhone);
            if (bywViteaData == null) {
                bywVitea.setUnlockedNum(0);
                bywVitea.setCreateTime(DateUtils.getNowDate());
                bywVitea.setUpdateTime(bywVitea.getCreateTime());
                viteaService.insertBywVitea(bywVitea);
            } else {
                int index = 0;
                BywVitea bywViteaUpdate = new BywVitea();
                bywViteaUpdate.setUserPhone(userPhone);
                if (StringUtils.isNotBlank(bywVitea.getUserName()) && !bywVitea.getUserName().equals(bywViteaData.getUserName())) {
                    bywViteaUpdate.setUserName(bywVitea.getUserName());
                    index++;
                }
                if (bywVitea.getAge() != null && !bywVitea.getAge().equals(bywViteaData.getAge())) {
                    bywViteaUpdate.setAge(bywVitea.getAge());
                    index++;
                }
                if (StringUtils.isNotBlank(bywVitea.getSex()) && !bywVitea.getSex().equals(bywViteaData.getSex())) {
                    bywViteaUpdate.setSex(bywVitea.getSex());
                    index++;
                }
                if (StringUtils.isNotBlank(bywVitea.getCityExpect()) && !bywVitea.getCityExpect().equals(bywViteaData.getCityExpect())) {
                    bywViteaUpdate.setCityExpect(bywVitea.getCityExpect());
                    index++;
                }
                if (StringUtils.isNotBlank(bywVitea.getIntendedCity()) && !bywVitea.getIntendedCity().equals(bywViteaData.getIntendedCity())) {
                    bywViteaUpdate.setIntendedCity(bywVitea.getIntendedCity());
                    index++;
                }

                if (StringUtils.isNotBlank(bywVitea.getPositionExpect()) && !bywVitea.getPositionExpect().equals(bywViteaData.getPositionExpect())) {
                    bywViteaUpdate.setPositionExpect(bywVitea.getPositionExpect());
                    index++;
                }
                if (StringUtils.isNotBlank(bywVitea.getSalaryExpect()) && !bywVitea.getSalaryExpect().equals(bywViteaData.getSalaryExpect())) {
                    bywViteaUpdate.setSalaryExpect(bywVitea.getSalaryExpect());
                    index++;
                }
                if (bywVitea.getHasDeliver() != null && !bywVitea.getHasDeliver().equals(bywViteaData.getHasDeliver())) {
                    bywViteaUpdate.setHasDeliver(bywVitea.getHasDeliver());
                    index++;
                }

                if (bywVitea.getDeliveryTime() != null && !bywVitea.getDeliveryTime().equals(bywViteaData.getDeliveryTime())) {
                    bywViteaUpdate.setDeliveryTime(bywVitea.getDeliveryTime());
                    index++;
                }

                if (index > 0) {
                    viteaService.updateBywVitea(bywViteaUpdate);
                }
            }
        }

        logger.info("结束同步简历数据:" + DateUtils.getTime());
    }

    /**
     * 最终做数据整合和取舍
     *
     * @return
     */
    private Map<String, BywVitea> ultimatelyPooledDate() {
        Map<String, BywVitea> viteaMap = new HashMap<>();
        Map<String, List<BywVitea>> pooledDataViteaMap = pooledData();
        for (Map.Entry<String, List<BywVitea>> entry : pooledDataViteaMap.entrySet()) {
            String userPhone = entry.getKey();

            List<BywVitea> bywViteaList = entry.getValue();

            if (CollectionUtils.isEmpty(bywViteaList)) {
                continue;
            }

            BywVitea bywViteaResult = new BywVitea();
            BeanUtils.copyProperties(bywViteaList.get(0), bywViteaResult);
            StringBuilder intendedCity = new StringBuilder(StringUtils.isBlank(bywViteaResult.getIntendedCity()) ? "" : bywViteaResult.getIntendedCity());
            Set<String> positionExpectSet = new HashSet<>();
            if (CollectionUtils.isNotEmpty(bywViteaResult.getPositionExpectSet())){
                positionExpectSet.addAll(bywViteaResult.getPositionExpectSet());
            }
            if (bywViteaList.size() == 1) {
                viteaMap.put(userPhone, bywViteaResult);
                bywViteaResult.setIntendedCity(intendedCity.toString());
                if (CollectionUtils.isNotEmpty(positionExpectSet)){
                    bywViteaResult.setPositionExpect(String.join(",", positionExpectSet));
                }
                continue;
            }
            int index = 0;
            for (BywVitea bywVitea : bywViteaList) {
                if (index == 0) {
                    index++;
                    continue;
                }

                if (StringUtils.isNotBlank(bywVitea.getIntendedCity()) && !intendedCity.toString().contains(bywVitea.getIntendedCity())){
                    intendedCity.append(",").append(bywVitea.getIntendedCity());
                }
                if (CollectionUtils.isNotEmpty(bywVitea.getPositionExpectSet())){
                    positionExpectSet.addAll(bywVitea.getPositionExpectSet());
                }
                // 如果当前对象时间更新，跟新部分字段
                if (bywViteaResult.getDeliveryTime().compareTo(bywVitea.getDeliveryTime()) < 0) {
                    bywViteaResult.setSalaryExpect(bywVitea.getSalaryExpect());
                    bywViteaResult.setSex(bywVitea.getSex());
                    bywViteaResult.setAge(bywVitea.getAge());
                    bywViteaResult.setHasDeliver(bywVitea.getHasDeliver());
                    bywViteaResult.setUserName(bywVitea.getUserName());
                    bywViteaResult.setCityExpect(bywVitea.getCityExpect());
                }
            }
            bywViteaResult.setIntendedCity(intendedCity.toString());
            if (CollectionUtils.isNotEmpty(positionExpectSet)){
                bywViteaResult.setPositionExpect(String.join(",", positionExpectSet));
            }
            viteaMap.put(userPhone, bywViteaResult);
        }

        return viteaMap;
    }

    /**
     * 把现有的简历库转换为MAP
     *
     * @return
     */
    private Map<String, BywVitea> initViteaMap() {
        Map<String, BywVitea> viteaMap = new HashMap<>();
        int pageNum = 1;
        do {
            // 设置当前页码和每页数量
            PageHelper.startPage(pageNum++, 10000);
            List<BywVitea> bywViteaList = viteaService.selectBywViteaList(new BywVitea());
            for (BywVitea bywVitea : bywViteaList) {
                viteaMap.put(bywVitea.getUserPhone(), bywVitea);
            }
            // 检查是否还有数据
            if (bywViteaList.size() < 10000) {
                break;
            }
        } while (true);

        return viteaMap;
    }

    /**
     * 把员工导入的简历  和  小程序的简历库 整合起来
     *
     * @return
     */
    private Map<String, List<BywVitea>> pooledData() {
        Map<String, List<BywVitea>> viteaMap = new HashMap<>();

        Map<Long, String> positionMap = positionMap();
        List<String> importUserPhoneList = new ArrayList<>();
        int pageNum = 1;
        do {
            // 设置当前页码和每页数量
            PageHelper.startPage(pageNum++, 10000);
            BywEmployeeImportVitea bywEmployeeImportViteaQuery = new BywEmployeeImportVitea();
            bywEmployeeImportViteaQuery.setUpdateTime(new Date(System.currentTimeMillis() - 6*60*1000));
            List<BywEmployeeImportVitea> bywEmployeeImportViteaList = employeeImportViteaService.selectBywEmployeeImportViteaList(bywEmployeeImportViteaQuery);
            logger.info("byw_employee_import_vita 有多少{}需要同步",bywEmployeeImportViteaList.size());

            for (BywEmployeeImportVitea employeeImportVitea : bywEmployeeImportViteaList) {
                BywVitea bywVitea = new BywVitea();
                bywVitea.setUserPhone(employeeImportVitea.getUserPhone());
                bywVitea.setUserName(employeeImportVitea.getUserName());
                bywVitea.setAge(employeeImportVitea.getAge());
                bywVitea.setSex(employeeImportVitea.getSex());
                bywVitea.setCityExpect(employeeImportVitea.getCityExpect());
                bywVitea.setIntendedCity(employeeImportVitea.getIntendedCity());
                Set<String> positionExpectSet = new HashSet<>();
                positionExpectSet.add(employeeImportVitea.getPositionExpect());
                bywVitea.setPositionExpectSet(positionExpectSet);
                bywVitea.setSalaryExpect(employeeImportVitea.getSalaryExpect());
                bywVitea.setHasDeliver(2);
                bywVitea.setDeliveryTime(employeeImportVitea.getUpdateTime());
                List<BywVitea> bywViteas = new ArrayList<>();
                bywViteas.add(bywVitea);
                viteaMap.put(employeeImportVitea.getUserPhone(), bywViteas);
                importUserPhoneList.add(bywVitea.getUserPhone());
            }
            // 检查是否还有数据
            if (bywEmployeeImportViteaList.size() < 10000) {
                break;
            }
        } while (true);

        if (CollectionUtils.isNotEmpty(importUserPhoneList)){
            int pageInTiktokNum = 1;
            do {
                // 设置当前页码和每页数量
                PageHelper.startPage(pageInTiktokNum++, 10000);
                List<BywTiktokUser> bywTiktokUserList = tiktokUserService.selectBywTiktokUserListUserPhones(importUserPhoneList.toArray(new String[0]));
                Map<String, Set<String>> phonePositionMap = getPhonePositionMap(positionMap, importUserPhoneList);
                for (BywTiktokUser tiktokUser : bywTiktokUserList) {
                    if (StringUtils.isBlank(tiktokUser.getUserPhone())) {
                        continue;
                    }
                    BywVitea bywVitea = new BywVitea();
                    bywVitea.setUserPhone(tiktokUser.getUserPhone());
                    bywVitea.setUserName(tiktokUser.getUserName());
                    bywVitea.setAge(tiktokUser.getAge());
                    bywVitea.setSex(tiktokUser.getSex());
                    bywVitea.setCityExpect(tiktokUser.getLocationCity());
                    bywVitea.setSalaryExpect(tiktokUser.getSalaryExpect());
                    bywVitea.setHasDeliver(tiktokUser.getHasDeliver());
                    if (tiktokUser.getHasDeliver() != null && tiktokUser.getHasDeliver() == 1){
                        bywVitea.setIntendedCity(tiktokUser.getCityExpect());

                        if (phonePositionMap.get(tiktokUser.getUserPhone()) != null && phonePositionMap.get(tiktokUser.getUserPhone()).size() != 0){
                            bywVitea.setPositionExpectSet(phonePositionMap.get(tiktokUser.getUserPhone()));
                        }

                        if (tiktokUser.getLastVisitTime() != null){
                            bywVitea.setDeliveryTime(tiktokUser.getLastVisitTime());
                        } else if (tiktokUser.getDeliveryTime() != null){
                            bywVitea.setDeliveryTime(tiktokUser.getDeliveryTime());
                        } else if (tiktokUser.getUpdateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getUpdateTime());
                        } else if (tiktokUser.getCreateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getCreateTime());
                        } else {
                            continue;
                        }
                    } else {
                        if (tiktokUser.getUpdateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getUpdateTime());
                        } else if (tiktokUser.getCreateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getCreateTime());
                        } else {
                            continue;
                        }
                    }
                    List<BywVitea> bywViteaList = viteaMap.get(tiktokUser.getUserPhone());
                    if (CollectionUtils.isEmpty(bywViteaList)) {
                        bywViteaList = new ArrayList<>();
                        bywViteaList.add(bywVitea);
                        viteaMap.put(tiktokUser.getUserPhone(), bywViteaList);
                    } else {
                        bywViteaList.add(bywVitea);
                        viteaMap.put(tiktokUser.getUserPhone(), bywViteaList);
                    }
                    stageVitaeRelation(tiktokUser.getBelongTiktokId(), tiktokUser.getUserPhone());
                }
                // 检查是否还有数据
                if (bywTiktokUserList.size() < 10000) {
                    break;
                }
            } while (true);
        }

        List<String> tiktokUserPhoneList = new ArrayList<>();
        int pageTiktokNum = 1;
        do {
            // 设置当前页码和每页数量
            PageHelper.startPage(pageTiktokNum++, 10000);
            BywTiktokUser bywTiktokUserQuery = new BywTiktokUser();
            //bywTiktokUserQuery.setBelongXcxId("tta2f5d4483dc6de8c01");
            bywTiktokUserQuery.setLastVisitTime(new Date(System.currentTimeMillis() - 6*60*1000));
            List<BywTiktokUser> bywTiktokUserList = tiktokUserService.selectBywTiktokUserListByXcxId(bywTiktokUserQuery);
            logger.info("byw_tiktok_user 有多少{}需要同步",bywTiktokUserList.size());
            List<String> userPhoneList = new ArrayList<>();
            for (BywTiktokUser tiktokUser : bywTiktokUserList) {
                userPhoneList.add(tiktokUser.getUserPhone());
            }

            if (CollectionUtils.isNotEmpty(userPhoneList)){
                Map<String, Set<String>> phonePositionMap = getPhonePositionMap(positionMap, userPhoneList);
                for (BywTiktokUser tiktokUser : bywTiktokUserList) {
                    if (StringUtils.isBlank(tiktokUser.getUserPhone())) {
                        continue;
                    }
                    BywVitea bywVitea = new BywVitea();
                    bywVitea.setUserPhone(tiktokUser.getUserPhone());
                    bywVitea.setUserName(tiktokUser.getUserName());
                    bywVitea.setAge(tiktokUser.getAge());
                    bywVitea.setSex(tiktokUser.getSex());
                    bywVitea.setCityExpect(tiktokUser.getLocationCity());
                    bywVitea.setSalaryExpect(tiktokUser.getSalaryExpect());
                    bywVitea.setHasDeliver(tiktokUser.getHasDeliver());
                    if (tiktokUser.getHasDeliver() != null && tiktokUser.getHasDeliver() == 1){
                        bywVitea.setIntendedCity(tiktokUser.getCityExpect());

                        if (phonePositionMap.get(tiktokUser.getUserPhone()) != null && phonePositionMap.get(tiktokUser.getUserPhone()).size() != 0){
                            bywVitea.setPositionExpectSet(phonePositionMap.get(tiktokUser.getUserPhone()));
                        }

                        if (tiktokUser.getLastVisitTime() != null){
                            bywVitea.setDeliveryTime(tiktokUser.getLastVisitTime());
                        } else if (tiktokUser.getDeliveryTime() != null){
                            bywVitea.setDeliveryTime(tiktokUser.getDeliveryTime());
                        } else if (tiktokUser.getUpdateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getUpdateTime());
                        } else if (tiktokUser.getCreateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getCreateTime());
                        } else {
                            continue;
                        }
                    } else {
                        if (tiktokUser.getUpdateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getUpdateTime());
                        } else if (tiktokUser.getCreateTime() != null) {
                            bywVitea.setDeliveryTime(tiktokUser.getCreateTime());
                        } else {
                            continue;
                        }
                    }
                    List<BywVitea> bywViteaList = viteaMap.get(tiktokUser.getUserPhone());
                    if (CollectionUtils.isEmpty(bywViteaList)) {
                        bywViteaList = new ArrayList<>();
                        bywViteaList.add(bywVitea);
                        viteaMap.put(tiktokUser.getUserPhone(), bywViteaList);
                    } else {
                        bywViteaList.add(bywVitea);
                        viteaMap.put(tiktokUser.getUserPhone(), bywViteaList);
                    }
                    stageVitaeRelation(tiktokUser.getBelongTiktokId(), tiktokUser.getUserPhone());
                    tiktokUserPhoneList.add(bywVitea.getUserPhone());
                }
            }
            // 检查是否还有数据
            if (bywTiktokUserList.size() < 10000) {
                break;
            }
        } while (true);

        if (CollectionUtils.isNotEmpty(tiktokUserPhoneList)){
            int pageInNum = 1;
            do {
                // 设置当前页码和每页数量
                PageHelper.startPage(pageInNum++, 10000);
                BywEmployeeImportVitea bywEmployeeImportViteaQuery = new BywEmployeeImportVitea();
                bywEmployeeImportViteaQuery.setUpdateTime(new Date(System.currentTimeMillis() - 6*60*1000));
                List<BywEmployeeImportVitea> bywEmployeeImportViteaList = employeeImportViteaService.selectBywEmployeeImportViteaByUserPhones(tiktokUserPhoneList.toArray(new String[0]));
                for (BywEmployeeImportVitea employeeImportVitea : bywEmployeeImportViteaList) {
                    BywVitea bywVitea = new BywVitea();
                    bywVitea.setUserPhone(employeeImportVitea.getUserPhone());
                    bywVitea.setUserName(employeeImportVitea.getUserName());
                    bywVitea.setAge(employeeImportVitea.getAge());
                    bywVitea.setSex(employeeImportVitea.getSex());
                    bywVitea.setCityExpect(employeeImportVitea.getCityExpect());
                    bywVitea.setIntendedCity(employeeImportVitea.getIntendedCity());
                    Set<String> positionExpectSet = new HashSet<>();
                    positionExpectSet.add(employeeImportVitea.getPositionExpect());
                    bywVitea.setPositionExpectSet(positionExpectSet);
                    bywVitea.setSalaryExpect(employeeImportVitea.getSalaryExpect());
                    bywVitea.setHasDeliver(2);
                    bywVitea.setDeliveryTime(employeeImportVitea.getUpdateTime());

                    List<BywVitea> bywViteaList = viteaMap.get(employeeImportVitea.getUserPhone());
                    if (CollectionUtils.isEmpty(bywViteaList)) {
                        bywViteaList = new ArrayList<>();
                        bywViteaList.add(bywVitea);
                        viteaMap.put(employeeImportVitea.getUserPhone(), bywViteaList);
                    } else {
                        bywViteaList.add(bywVitea);
                        viteaMap.put(employeeImportVitea.getUserPhone(), bywViteaList);
                    }
                }
                // 检查是否还有数据
                if (bywEmployeeImportViteaList.size() < 10000) {
                    break;
                }
            } while (true);
        }

        return viteaMap;
    }

    private void stageVitaeRelation(String blelongTiktokId, String userPhone){
        if (StringUtils.isBlank(blelongTiktokId)){
            return;
        }
        List<BywStage> bywStages = stageService.selectBywStageByTiktokAccount(blelongTiktokId);
        if (CollectionUtils.isEmpty(bywStages)){
            return;
        }
        BywStage bywStage = bywStages.get(0);
        BywViteaOwnershipRelation bywViteaOwnershipRelation = new BywViteaOwnershipRelation();
        bywViteaOwnershipRelation.setViteaPhone(userPhone);
        bywViteaOwnershipRelation.setUserId(bywStage.getStageId());
        bywViteaOwnershipRelation.setType(0);
        List<BywViteaOwnershipRelation> bywViteaOwnershipRelations = viteaOwnershipRelationService.selectBywViteaOwnershipRelationList(bywViteaOwnershipRelation);
        if (CollectionUtils.isEmpty(bywViteaOwnershipRelations)){
            bywViteaOwnershipRelation.setState(0);
            bywViteaOwnershipRelation.setCreatTime(DateUtils.getNowDate());
            viteaOwnershipRelationService.insertBywViteaOwnershipRelation(bywViteaOwnershipRelation);
        }
    }


    private Map<Long, String> positionMap(){
        List<BywPositionType> list = positionTypeService.selectBywPositionList(new BywPositionType());
        Map<Long, String> positionMap = new HashMap<>();

        for (BywPositionType position : list){
            positionMap.put(position.getId(), position.getPositionName());
        }
        return positionMap;
    }

    private Map<String, List<Long>> getPositionTypeIdList(List<String> userPhoneList){
        Map<String, List<Long>> positionTypeMap = new HashMap<>();
        List<BywDeliverPositionType> bywDeliverPositionTypes = tiktokUserService.selectDeliverPositionType(userPhoneList.toArray(new String[0]));
        for (String userPhone : userPhoneList){
            List<Long> positionTypeIdList = new ArrayList<>();
            for (BywDeliverPositionType bywDeliverPositionType: bywDeliverPositionTypes){
                if (bywDeliverPositionType.getPositionTypeSecond() == null){
                    continue;
                }
                if (userPhone.equals(bywDeliverPositionType.getDeliverPhone())){
                    positionTypeIdList.add(bywDeliverPositionType.getPositionTypeSecond());
                }
            }
            if (CollectionUtils.isEmpty(positionTypeIdList)){
                continue;
            }
            positionTypeMap.put(userPhone, positionTypeIdList);
        }

        return positionTypeMap;
    }

    private Map<String,Set<String>> getPhonePositionMap(Map<Long, String> positionMap, List<String> userPhoneList){
        Map<String, List<Long>> positionTypeIdList = getPositionTypeIdList(userPhoneList);
        Map<String, Set<String>> phonePositionMap = new HashMap<>();
        for (String key:positionTypeIdList.keySet()){
            phonePositionMap.put(key, getPosition(positionMap, positionTypeIdList.get(key)));
        }
        return phonePositionMap;
    }

    private Set<String> getPosition(Map<Long, String> positionMap, List<Long> positionTypeIdList){
        Set<String> positionSet = new HashSet<>();
        if (CollectionUtils.isEmpty(positionTypeIdList)){
            return positionSet;
        }
        if (positionTypeIdList.size() == 1){
            positionSet.add(positionMap.get(positionTypeIdList.get(0)));
            return positionSet;
        }
        int index = 0;
        for (Long positionTypeId : positionTypeIdList){
            if (index == 0) {
                index++;
                continue;
            }
            positionSet.add(positionMap.get(positionTypeId));
        }

        return positionSet;
    }

}
